<template>
    <div>
        <v-data-table
                :headers="headers"
                :items="desserts"
                :search="search"
                :footer-props="footer"
                class="elevation-1"
        >
            <template v-slot:top>
                <v-toolbar flat color="white">
                    <v-toolbar-title>{{ title }}</v-toolbar-title>
                    <v-divider class="mx-4" inset vertical></v-divider>

                    <v-dialog v-model="dialog" max-width="500px">
                        <template v-slot:activator="{ on, attrs }">
                            <!-- <v-icon color="primary" v-bind="attrs" v-on="on">mdi-database-plus</v-icon> -->
                            <v-btn icon large color="primary" v-bind="attrs" v-on="on"
                            >
                                <v-icon>mdi-database-plus</v-icon>
                            </v-btn
                            >
                        </template>
                        <v-card>
                            <v-card-title>
                                <span class="headline">{{ formTitle }}</span>
                            </v-card-title>

                            <v-card-text>
                                <v-container>
                                    <v-row>
                                        <!-- 仿写下面的col -->
                                        <v-col cols="12" sm="12" md="12">
                                            <v-text-field
                                                    v-model="editedItem.name"
                                                    label="角色"
                                            ></v-text-field>
                                        </v-col>
                                        <v-col cols="12" sm="12" md="12">
                                            <v-text-field
                                                    v-model="editedItem.desc"
                                                    label="简介"
                                            ></v-text-field>
                                        </v-col>
                                    </v-row>
                                </v-container>
                            </v-card-text>
                            <v-card-actions>
                                <v-spacer></v-spacer>
                                <v-btn color="error" text @click="close">Cancel</v-btn>
                                <v-btn color="success" text @click="save">Save</v-btn>
                            </v-card-actions>
                        </v-card>
                    </v-dialog>
                    <v-spacer></v-spacer>
                    <v-text-field
                            v-model="search"
                            append-icon="mdi-magnify"
                            label="Search"
                            single-line
                            hide-details
                    ></v-text-field>
                </v-toolbar>
            </template>
            <template v-slot:item.actions="{ item }">
                <v-icon color="primary" class="mr-2" @click="editItem(item)">
                    mdi-pencil
                </v-icon>
                <v-icon color="acent" class="mr-2" @click="editWindow(item)">
                    mdi-tune
                </v-icon>
                <v-icon color="warning" @click="deleteItem(item)"> mdi-delete</v-icon>
            </template>
            <template v-slot:no-data>
                <v-btn color="primary" @click="refresh">Reset</v-btn>
            </template>
        </v-data-table>
        <v-dialog v-model="drawer" fullscreen hide-overlay transition="dialog-bottom-transition">
            <v-card>
                <v-toolbar dark color="primary">
                    <v-toolbar-title>{{roleSelected}}</v-toolbar-title>
                    <v-spacer></v-spacer>
                    <v-toolbar-items>
                        <v-btn icon dark @click="closeWindow">
                            <v-icon>mdi-close</v-icon>
                        </v-btn>
                    </v-toolbar-items>
                </v-toolbar>

                <v-card-text class="mt-4">
                    <!--          <v-row align="center">-->
                    <v-window
                            v-model="window"
                            class="elevation-1"
                            show-arrows
                    >
                        <v-window-item>
                            <v-card flat>
                                <v-card-title>
                                    菜单权限
                                    <v-spacer></v-spacer>
                                    <v-btn color="success" @click="saveWindow">Save</v-btn>
                                </v-card-title>
                                <v-divider></v-divider>
                                <v-card-text>
                                    <v-treeview
                                            v-model="menusSelected"
                                            return-object
                                            selectable
                                            open-all
                                            :items="menus"
                                    ></v-treeview>
                                </v-card-text>
                            </v-card>
                        </v-window-item>
                        <v-window-item>
                            <v-card flat>
                                <v-card-title>
                                    菜单权限
                                </v-card-title>
                                <v-divider></v-divider>
                                <v-card-text>
                                    <v-treeview
                                            v-model="apisSelected"
                                            return-object
                                            selectable
                                            open-all
                                            :items="apis"
                                    ></v-treeview>
                                </v-card-text>
                            </v-card>
                        </v-window-item>
                    </v-window>
                    <!--          </v-row>-->
                </v-card-text>

            </v-card>
        </v-dialog>
    </div>
</template>

<script>
    // 引用各自的API
    import {
        GetListRole,
        GetOneRole,
        CreateOneRole,
        UpdateOneRole,
        RemoveOneRole,
    } from "@/api/role.js";
    import {GetListMenu} from "@/api/menu"
    import {GetListApi} from "@/api/resource"
    import {mapGetters} from "vuex";

    export default {
        data: () => ({
            dialog: false,
            drawer: false,
            length: 2,
            window: 0,
            search: "",
            desserts: [],
            editedIndex: -1,
            editedItem: {name: "", desc: "", parentId: 0},
            menus: [],
            menusSelected: [],
            roleSelected: "",
            apis: [],
            apisSelected: [],
            // Todo 修改下面三个字段
            // ============================================================================
            title: "角色",
            headers: [
                {
                    text: "角色",
                    align: "start",
                    sortable: false,
                    value: "name",
                },
                {
                    text: "简介",
                    align: "start",
                    sortable: false,
                    value: "desc",
                },
                {text: "Actions", value: "actions", sortable: false},
            ],
            defaultItem: {
                name: "",
                desc: "",
                parentId: 0,
            },
            // ============================================================================
        }),
        computed: {
            ...mapGetters("app", ["footer"]),
            formTitle() {
                return this.editedIndex === -1
                    ? "新建" + this.title
                    : "更新" + this.title;
            },
        },

        watch: {
            dialog(val) {
                val || this.close();
            },
        },

        created() {
            this.initialize();
            this.refresh();
        },
        // beforeRouteEnter(to, from, next) {
        //   console.info("组件进入守卫工作")
        //   next()
        // },
        // beforeRouteLeave(to, from, next) {
        //   console.info("组件离开守卫工作")
        //   next()
        // },

        methods: {
            initialize() {
                const transTree = (data) => {
                    let result = []
                    let map = {}
                    if (!Array.isArray(data)) {//验证data是不是数组类型
                        return []
                    }
                    data.forEach(item => {//建立每个数组元素id和该对象的关系
                        map[item.id] = item //这里可以理解为浅拷贝，共享引用
                    })
                    data.forEach(item => {
                        let parent = map[item.parentId] //找到data中每一项item的爸爸
                        if (parent) {//说明元素有爸爸，把元素放在爸爸的children下面
                            (parent.children || (parent.children = [])).push(item)
                        } else {//说明元素没有爸爸，是根节点，把节点push到最终结果中
                            result.push(item) //item是对象的引用
                        }
                    })
                    return result //数组里的对象和data是共享的
                }
                const groupTree = (data) => {
                    let result = []
                    let map = {}
                    if (!Array.isArray(data)) {//验证data是不是数组类型
                        return []
                    }
                    data.forEach(item => {
                        if (item.title in map) {
                            map[item.title].children.push(item)
                        } else {
                            map[item.title] = {id: -1 * item.id, name: item.title, children: []}
                            map[item.title].children.push(item)
                        }
                    })
                    for (let k in map) {
                        result.push(map[k])
                    }

                    return result
                }
                let temp
                GetListMenu().then(res => {
                    temp = res.body
                    temp.map(m => {
                        m.name = m.meta.title
                    })
                    this.menus = transTree(temp)
                })
                GetListApi().then(res => {
                    temp = res.body
                    temp.map(m => {
                        m.name = m.desc + "[" + m.method + " " + m.path + "]"
                    })
                    this.apis = groupTree(temp)
                })
            },
            refresh() {
                // Todo 这里从后台请求数据，写入this.desserts
                GetListRole().then((res) => {
                    this.desserts = res.body;
                });
            }
            ,

            editItem(item) {
                this.editedIndex = this.desserts.indexOf(item);
                this.editedItem = Object.assign({}, item);
                this.dialog = true;
            }
            ,
            close() {
                this.dialog = false;
                this.$nextTick(() => {
                    this.editedItem = Object.assign({}, this.defaultItem);
                    this.editedIndex = -1;
                });
            }
            ,

            //  下面两个方法需要增加相应的后台交互操作
            save() {
                if (this.editedIndex > -1) {
                    //   update
                    // Object.assign(this.desserts[this.editedIndex], this.editedItem);
                    UpdateOneRole(this.editedItem).then(res => {
                        this.$msg.info(res.msg)
                        this.refresh()
                    })
                } else {
                    //   create
                    // this.desserts.push(this.editedItem);
                    CreateOneRole(this.editedItem).then(res => {
                        this.$msg.info(res.msg)
                        this.refresh()
                    })

                }
                this.close();
            }
            ,
            deleteItem(item) {
                // const index = this.desserts.indexOf(item);
                confirm("确认删除?") &&
                // this.desserts.splice(index, 1);
                RemoveOneRole(item.id).then(res => {
                    this.$msg.info(res.msg)
                    this.refresh()
                })
            }
            ,
            editWindow(item) {
                this.editedRole= item.id
                this.roleSelected = item.name
                this.menusSelected = item.menus

                // TODO 开启dialog
                this.drawer = true
            },
            closeWindow() {
                this.editedRole = -1;
                this.drawer = false
            },
            saveWindow() {
                console.log(this.menusSelected)
                GetOneRole(this.editedRole).then(res=>{
                    let role = res.body
                    console.log(role)
                    Object.assign(role.menus, {}, this.menusSelected)
                    console.log(role.menus)
                })

            }
        },
    }
    ;
</script>
